# 帮我生成python代码，实现对代理ip的有效性进行检测，
# 过程中，
# 待检测的代理IP在项目的./IP代理/代理池.txt中，每行一个代理，如：http://183.164.242.184:8089。
# 用fake_useragent来生成非移动端的User-Agent。
# 用curl ifconfig.me来获取本机IP。
# 如果获取到的本机IP与当前验证的代理IP不一致，说明代理无效，则打印输出“xxx 无效”，如果有效，则打印输出“xxx 有效”。并将有效的代理添加到一个数组里

import requests
from fake_useragent import UserAgent
import re
import time


def get_public_ip():
    response = requests.get("https://myip.ipip.net/")
    if response.status_code == 200:
        return extract_ip(response.text)
    else:
        return None


def extract_ip(proxy):
    match = re.search(r'(\d+\.\d+\.\d+\.\d+)', proxy)
    return match.group(1) if match else None


def check_proxy(proxy, public_ip):
    ua = UserAgent()
    while True:
        random_ua = ua.random
        if 'Mobile' not in random_ua:
            break

    headers = {'User-Agent': random_ua}
    proxies = {
        'http': proxy,
        # 'https': proxy,
    }

    # while True:
    try:
        response = requests.get("https://myip.ipip.net/", headers=headers, proxies=proxies, timeout=5)
        print(f"PING: {response.text.strip()}")
        if response.status_code == 200:
            response_ip = response.text.strip()
            proxy_ip = extract_ip(proxy)
            if proxy_ip in response_ip:
                print(f"代理结果：{proxy_ip} 代理成功啦！!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
                return True
            elif public_ip in response_ip:
                print(f"代理结果：{proxy_ip} 代理失败-----------------------\n")
                return False
            else:
                print("请求无效...\n")
                return False
        else:
            print("请求失败...\n")
            return False
    except requests.RequestException:
        print("请求超时...\n")
        return False


def main():
    valid_proxies = []
    with open('代理池_20241226_7983.txt', 'r') as file:
        proxies = file.readlines()

    if not proxies:
        print("代理池为空")
        return

    public_ip = get_public_ip()
    if not public_ip:
        print("无法获取本机公网IP")
        return

    for proxy in proxies:
        proxy = proxy.strip()
        print(f"本机公网IP: {public_ip}")
        print(f"正在验证代理IP: {proxy}")
        if check_proxy(proxy, public_ip):
            valid_proxies.append(proxy)
        time.sleep(1)  # 限制请求频率，每次请求后等待1秒

    print("有效的代理IP列表:", valid_proxies)


if __name__ == "__main__":
    main()
